<template>
  <div class="analysis-wrap js-clickbody" @click="bodyClick('body')">
    <div class="chose-course-top">
      <div class="header-left">
        <span id="analysisBack" class="back-arrow" @click="quitStudy"></span>
        <a class="topleft-title" @click="readMain">文章梗概</a>
        <a class="block-blank"></a>
      </div>
      <div class="course-title">
        {{ detail.level_title }}
      </div>
      <div class="btn-group">
        <!-- 可答题次数小于等于0 -->
        <a v-if="$route.query.over" @click="showNewWords">{{ showWords ? "隐藏生词" : "显示生词" }}</a>
        <a @click="goWordList">生词列表</a>
        <template v-if="!$route.query.over">
          <template v-if="translationType === 'word'">
            <a @click="wordParaToggle('paragraph')">单句翻译</a>
          </template>
          <template v-else>
            <a @click="wordParaToggle('word')">单词翻译</a>
          </template>
        </template>
      </div>
    </div>
    <div class="list-wrap">
      <div class="article-content two-colum-width scrolToMinView">
        <p class="article-title">
          {{ this.detail.question_title }}
        </p>
        <div class="read-tip">
          <div>
            <img src="~assets/super-read/read-time.png" alt="" />
            <span>参考时长：</span>
            <span>{{ detail.read_time }}min</span>
          </div>
          <div>
            <img src="~assets/super-read/difficulty-icon.png" alt="" />
            <span>难度：</span>
            <div class="read-stars">
              <span
                v-for="(star, index) in new Array(5).fill('star')"
                :key="`${star}-${index}`"
                :class="{
                  'read-star': +detail.read_difficulty_id >= index + 1,
                  'read-star-none': +detail.read_difficulty_id < index + 1,
                }"
              ></span>
            </div>
          </div>
        </div>
        <div class="show-check-words" v-show="translationType === 'word'">
          <p
            class="article-paragraph"
            v-for="(paragraph, index) in content"
            :key="`paragraph-p-${index}`"
          >
            <span v-for="(word, i) in paragraph" :key="word + i">
              <template>
                <template v-if="(/###([A-Za-z]+['’]?[A-Za-z]*)###/).test(word)">
                  <span class="blank">{{word.replace(/###([A-Za-z]+['’]?[A-Za-z]*)###/, '$1').replace(splitStr, ' ')}}</span>
                </template>
                <a-popover
                  transitionName=""
                  v-else
                  overlayClassName="lookup-popover"
                  placement="bottom"
                  :visible="visibleKey === `paragraphVisible${index}-${i}`"
                  :destroyTooltipOnHide="true"
                  trigger="click"
                >
                  <!-- <template v-if="word.split(',').length > 1">
                      <span
                        class="pop-content-word"
                        :style="{
                          'padding-left': itemI === 1 ? 0 : '4px',
                          'padding-right': itemI === 0 ? 0 : '4px',
                        }"
                        v-for="(wordItem, itemI) in word.split(',')"
                        :key="wordItem + itemI"
                        @click="checkWord(wordItem, `paragraphVisible${index}-${i}`)"
                      >
                        {{ wordItem }}{{ itemI == 0 ? "," : "" }}
                      </span>
                  </template> -->
                  <span
                    :yxp_attr="viLock?'disable':''"
                    :id="`word-paragraphVisible${index}-${i}`"
                    class="pop-content-word js_show_word synclock"
                    @click="checkWord(word, `paragraphVisible${index}-${i}`)"
                    >{{ word }}</span
                  >
                  <div slot="content">
                    <div class="lookup-content">
                      <div class="title">
                        {{ translate.prototype_word || translate.select_word }}
                        <img
                          v-show="translate.prototype_word"
                          class="icon-img"
                          @click="translateVoice"
                          src="~assets/reverse/audio-play1.png"
                          alt=""
                        />
                      </div>
                      <div class="translate">
                        {{ translate.translate || "未找到该生词" }}
                      </div>
                      <div class="btn-group">
                        <a
                          :disabled="!translate.prototype_word || $route.query.over"
                          @click.stop="addWord"
                          ><img
                            class="icon-img"
                            src="~assets/reverse/add1.png"
                            alt=""
                          />添加生词</a
                        >
                        <a @click="translateDetail"
                          ><img
                            class="icon-img"
                            src="~assets/reverse/detail1.png"
                            alt=""
                          />单词详解</a
                        >
                      </div>
                    </div>
                  </div>
                </a-popover>
              </template>
            </span>
          </p>
        </div>
        <div class="show-check-paragraph" v-show="translationType === 'paragraph'">
          <span
            class="article-paragraph js-translate-paragraph"
            v-for="(paragraph, index) in translateParagraph"
            :key="`paragraph-translate-${index}`"
          >
            <paragraphTranslate
              :key="paragraph + index"
              :word="paragraph"
              :curr="indexShow"
              @currIndex="clickCurrIndex"
              :id="detail.id"
              :splittranslate="detail.splittranslate"
            >
            </paragraphTranslate>
          </span>
        </div>
      </div>
      <div class="article-answer two-colum-width">
        <div class="analysis-main-tab">
          <span
            @click="changeTopTab('analysis')"
            :class="{ 'analysis-tab__active': analysisTabKey === 'analysis' }"
            >答案解析</span
          >
          <span
            @click="changeTopTab('translate')"
            :class="{ 'analysis-tab__active': analysisTabKey === 'translate' }"
            >全文翻译</span
          >
        </div>
        <a-tabs type="card" :activeKey="analysisTabKey">
          <a-tab-pane tab="" key="analysis">
            <div class="answer-main">
              <a-tabs type="card" :activeKey="subTabKey">
                <a-tab-pane
                  tab=""
                  v-for="(sub, subIndex) in subjects"
                  :key="subIndex"
                >
                  <div class="answer-sub">
                    <div class="answer-sub-section read-sub-section" id="selectSection">
                      <div>
                        <p @click="subTitleClick($event)" class="sub-title">
                          {{ sub.id }}.
                          <span
                              v-for="(subQ, subQIndex) in sub.subject"
                              :key="`checksubword-${subQ}${subQIndex}`"
                          >
                            <template>
                              <a-popover
                                transitionName=""
                                overlayClassName="lookup-popover"
                                placement="bottom"
                                v-if="(/([A-Za-z]+['’]?[A-Za-z]*)/).test(subQ)"
                                :visible="visibleKey === `subWordVisible${subIndex}-${subQIndex}`"
                                :destroyTooltipOnHide="true"
                                trigger="click">
                                <span
                                  :yxp_attr="viLock?'disable':''"
                                  :id="`word-subWordVisible${subIndex}-${subQIndex}`"
                                  class="pop-content-word js_show_word synclock"
                                  @click="checkWord(subQ, `subWordVisible${subIndex}-${subQIndex}`)"
                                  >{{ subQ }}</span
                                >
                                <div slot="content">
                                  <div class="lookup-content">
                                    <div class="title">
                                      {{
                                        translate.prototype_word ||
                                          translate.select_word
                                      }}
                                      <img
                                        v-show="translate.prototype_word"
                                        class="icon-img"
                                        @click="translateVoice"
                                        src="~assets/reverse/audio-play1.png"
                                        alt=""
                                      />
                                    </div>
                                    <div class="translate">
                                      {{ translate.translate || "未找到该生词" }}
                                    </div>
                                    <div class="btn-group">
                                      <a
                                        :disabled="!translate.prototype_word || $route.query.over"
                                        @click.stop="addWord"
                                        ><img
                                          class="icon-img"
                                          src="~assets/reverse/add1.png"
                                          alt=""
                                        />添加生词</a
                                      >
                                      <a @click="translateDetail"
                                        ><img
                                          class="icon-img"
                                          src="~assets/reverse/detail1.png"
                                          alt=""
                                        />单词详解</a
                                      >
                                    </div>
                                  </div>
                                </div>
                              </a-popover>
                              <span v-else>{{ subQ }}</span>
                            </template>
                          </span>
                        </p>
                        <label
                          class="sub-item"
                          v-for="(opt, i) in sub.options"
                          :key="`labelopt${i}`"
                        >
                          <span
                            :class="{
                              'opt-radio__checked': +sub.right_option === i,
                              'opt-radio__checked__error':
                                selectList[subIndex].right === false &&
                                +selectList[subIndex].answer === i && !$route.query.over,
                            }"
                            class="opt-radio"
                          >
                            <template v-if="i === 0">A</template>
                            <template v-else-if="i === 1">B</template>
                            <template v-else-if="i === 2">C</template>
                            <template v-else-if="i === 3">D</template>
                          </span>
                          <div class="sub-options-item">
                            <template>
                              <a-popover
                                transitionName=""
                                overlayClassName="lookup-popover"
                                placement="bottom"
                                :visible="visibleKey === `subWordVisible${optWord}-${OptIndex}-${i}`"
                                v-for="(optWord, OptIndex) in opt"
                                :key="`checksubOpt-${optWord}${OptIndex}`"
                                :destroyTooltipOnHide="true"
                                trigger="click"
                              >
                                <span
                                  :yxp_attr="viLock?'disable':''"
                                  :id="`word-subWordVisible${optWord}-${OptIndex}-${i}`"
                                  class="pop-content-word pop-split-word js_show_word synclock"
                                  @click="checkWord(optWord, `subWordVisible${optWord}-${OptIndex}-${i}`)"
                                  >{{ optWord }}</span
                                >
                                <div slot="content">
                                  <div class="lookup-content">
                                    <div class="title">
                                      {{
                                        translate.prototype_word ||
                                          translate.select_word
                                      }}
                                      <img
                                        v-show="translate.prototype_word"
                                        class="icon-img"
                                        @click="translateVoice"
                                        src="~assets/reverse/audio-play1.png"
                                        alt=""
                                      />
                                    </div>
                                    <div class="translate">
                                      {{
                                        translate.translate || "未找到该生词"
                                      }}
                                    </div>
                                    <div class="btn-group">
                                      <a
                                        :disabled="!translate.prototype_word || $route.query.over"
                                        @click.stop="addWord"
                                        ><img
                                          class="icon-img"
                                          src="~assets/reverse/add1.png"
                                          alt=""
                                        />添加生词</a
                                      >
                                      <a @click="translateDetail"
                                        ><img
                                          class="icon-img"
                                          src="~assets/reverse/detail1.png"
                                          alt=""
                                        />单词详解</a
                                      >
                                    </div>
                                  </div>
                                </div>
                              </a-popover>
                            </template>
                          </div>
                        </label>
                      </div>
                      <div class="answer-reason">
                        <p>正确答案：
                          <template v-if="+sub.right_option === 0">A</template>
                          <template v-else-if="+sub.right_option === 1">B</template>
                          <template v-else-if="+sub.right_option === 2">C</template>
                          <template v-else-if="+sub.right_option === 3">D</template>
                        </p>
                        <p>{{ sub.reason }}</p>
                      </div>
                    </div>
                  </div>
                </a-tab-pane>
              </a-tabs>
              <div class="answer-option read-option">
                <p class="answer-nav">
                  <span v-show="+subTabKey !== 0" @click="subTabChange('pre')"
                    >上一题</span
                  ><span>{{ subTabKey + 1 }}/{{ subjects.length }}</span
                  ><span
                    v-show="+subTabKey + 1 !== subjects.length"
                    @click="subTabChange('next')"
                    >下一题</span
                  >
                </p>
                <div class="stu-answer-content" :class="{'content__read': $route.query.over}">
                    <div class="stu-answer">
                      <span
                        class="answer-num"
                        v-for="(answer, answerI) in selectList"
                        :key="`answer${answer.id}${answerI}`"
                        @click="changeSubTab(answerI)"
                        :class="{
                          'answer-item__true': answer.right || $route.query.over,
                          'answer-item__false': !answer.right && !$route.query.over,
                          'answer-item__select': answerI === subTabKey,
                        }"
                      >
                        {{ answer.id }}
                      </span>
                    </div>
                    <a-button
                      @click="startClickHandle"
                      class="sub-btn"
                      type="primary"
                      v-show="+readCurrent.course_type === 0 ? true : !$route.query.over"
                      >完成训练</a-button
                    >
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane tab="" key="translate">
            <div class="answer-main">
              <div class="answer-sub">
                <div class="answer-sub-section translate-section">
                  <p
                    v-for="(translate, translateIndex) in translateArticle"
                    :key="`translate${translateIndex}`"
                    v-html="translate"
                  ></p>
                </div>
                <div class="translate-option read-option">
                  <a-button
                    @click="startClickHandle"
                    class="sub-btn"
                    type="primary"
                    v-show="+readCurrent.course_type === 0 ? true : !$route.query.over"
                    >完成训练</a-button
                  >
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { checkWord, addWord } from "@/services/reverse";
import { fetchReadWord, handUpQuestion, readReport } from "@/services/super-read";
import { SUCCESS_CODE } from "@/utils/const";
import { Popover, message, Tabs } from "ant-design-vue";
import paragraphTranslate from "./paragraphTranslate";
import Timetips from "@/components/Timetips";
import _ from 'lodash'
import $ from "jquery";
export default {
  name: "analysis",
  components: {
    APopover: Popover,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    paragraphTranslate,
    Timetips
  },
  data() {
    return {
      splitStr: 'zaqwsx',
      viLock: false,
      audio: {},
      lastvi: "",
      visibles: {},
      visibleKey: "-1",
      indexShow: '',
      detail: {
        splittranslate: [],
        result: {}
      },
      subjects: [],
      showWords: false,
      content: [],
      translateParagraph: [],
      translationType: "word",
      translateParagraphText: "",
      analysisTabKey: "analysis",
      subTabKey: 0,
      selectList: [],
      canSub: false,
      subTimer: null,
      readTime: 0,
      translate: {},
      translateArticle: [],
      isStart: false,
      isSelectWords: this.$route.query.select_words,
      diffWords: new Set(),
      isnew:0,
      parent_id:0,
      title:'',
      package_id:0
    };
  },
  computed: {
    ...mapState({
      readCourseInfo: (state) => state.readCourseInfo,
      userInfo: (state) => state.userInfo,
      readCurrent: (state) => state.readCurrent,
      readReport: (state) => state.readReport,
    }),
  },
  watch: {
    subjects: {
      handler: (val) => {
        console.log(val);
        let answersL = val.filter((v) => v.answer >= 0).length;
        if (answersL === val.length) {
          this.canSub = true;
        }
      },
      deep: true,
    },
  },
  methods: {
    ...mapMutations(["setTranslateModal", "setReadBroadModal", "setReadReport"]),
    outPopClick(oi) {
      if (typeof oi == "object") {
        if (this.visibles[this.lastvi] == true) {
          let dom = document.getElementsByClassName("ant-popover-open")[0]
          dom ? dom.click() : ''
        }
      } else {
        for (let i in this.visibles) {
          if (typeof oi == "string" && oi == i) continue;
          this.visibles[i] = false;
        }
      }
    },
    clickCurrIndex(index) {
      console.log(index)
      this.indexShow = index
    },
    async initList() {
      let that = this,
          id = '',
          res = {},
          detail;
          if (this.readCurrent.id !== this.readReport.id) {
            id = this.readCurrent.id
            res = await readReport({
              id: id,
              question_type: this.readCourseInfo.type,
            })
            if (res.code !== SUCCESS_CODE) {
              return
            } else {
              this.setReadReport(_.cloneDeep(res.data))
              detail = res.data
            }
          } else {
            detail = _.cloneDeep(this.readReport)
          }
          this.detail = detail;
          let article_title = this.detail.question_content;
          let string = article_title.split(/\n/);
          this.content = string.map((v) => {
            return v.replace(/###([^#]+)###/g, (vv) => {
              return vv.replace(' ', that.splitStr)
            }).split(" ").filter(v => !!v);
          });
          // // this.content = string.map((v) => {
          // //   return v.split(" ");
          // // });
          // // 学生答案
          let selectList = [];
          let stuAnswer = this.detail.result.select_option.split(",");
          let subjects = this.detail.subjects.map((v, index) => {
            let subject = v.subject.replace(/([A-Za-z0-9]+['’]?[A-Za-z0-9]*)/gi, " $1 ").split(" ");
            let options = v.options.map((v) => {
              return v.split(" ").filter(v => !!v);
            });
            if (+v.right_option === +stuAnswer[index]) {
              selectList.push({ id: v.id, right: true, answer: stuAnswer[index] });
            } else {
              selectList.push({ id: v.id, right: false, answer: stuAnswer[index] });
            }
            return Object.assign(v, { subject, options });
          });
          this.selectList = selectList;
          this.subjects = subjects;
          this.translateArticle = this.detail.translation.split(/[\r|\n]/);
          // 单句翻译用
          this.translateParagraph = article_title.match(/([\s\S]*?)(!|\?|。|;|\. )+([.]{3})?[ ]?/g).map(v => {
            let vv = v.replace(/###([^#]+)###/g, ' <span class="blank">$1</span> ')
            return vv.replace(/\n+(\s*)/g, ' <br/>  ')
          })
    },
    goWordList() {
      this.$router.push({
        path: "/super-read/beforeStudy",
        query: {
          type: this.readCourseInfo.type,
          id: this.readCurrent.id,
          read: true,
          modal: 3
        },
      });
    },
    readMain() {
      this.setReadBroadModal({
        visible: true,
        mainidea: this.detail.mainidea,
      });
    },
    showNewWords() {
      let checkWords = $(".js_show_word");
      if (this.showWords) {
        this.showWords = false;
        // pop 组件会修改动态类名 这里更改 style
        checkWords.css({
          "background-color": "",
          color: "#333",
        });
      } else {
        fetchReadWord({
          question_id: this.readCurrent.id,
        }).then((res) => {
          if (res.code === SUCCESS_CODE) {
            if (!res.data.length) {
              this.$message.error('您还没有加入生词哦~')
              return
            }
            let selectWords = res.data.map((v) => v.select_word);
            checkWords.each((i, el) => {
              let text = this.replaceText($(el).text());
              if (selectWords.includes(text)) {
                $(el).css({
                  "background-color": "#27BFA3",
                  color: "#fff",
                });
              }
            });
            this.showWords = true;
          }
        });
      }
    },
    replaceText(word) {
      const pattern = /[^a-zA-Z']/g;
      return word.replace(pattern, "");
    },
    checkWord(value, i) {
      if (!value || this.viLock) return;
      this.viLock = true;
      checkWord({ word: value }).then((res) => {
          this.translate = res.data;
          this.visibleKey = i
          // this.visibles[i] = !this.visibles[i];
          this.viLock = false;
      });
    },
    addWord() {
      addWord({
        prototype_word: this.translate.prototype_word,
        select_word: this.translate.select_word,
        question_id: this.detail.id,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
        }
      });
    },
    translateVoice() {
      this.audio.src = this.translate.project_voice;
      this.audio.play();
    },
    translateDetail() {
      this.setTranslateModal({
        visible: true,
        word: this.translate.select_word,
      });
      document.getElementById("app").click();
    },
    selectWords(e, word) {
      console.log(e, word);
      word = this.replaceText(word);
      if (this.diffWords.has(word)) {
        message.error("不可以添加重复的词");
        return;
      }
      if (this.diffWords.size === 10) {
        message.error("最多可选10单词");
        return;
      }
      this.diffWords.add(word);
      $(e.srcElement).addClass("diff_word_select");
    },
    wordParaToggle(type) {
      this.translationType = type;
      $(".ant-popover").empty();
      $('.ant-popover-open').removeClass('ant-popover-open')
    },
    paragraphClick(e) {
      let index = $(".pop-content-paragraph").index($(e.srcElement));
      this.translateParagraphText = this.detail.splittranslate[index];
    },
    changeTopTab(key) {
      this.analysisTabKey = key;
    },
    subTabChange(cmd) {
      if (cmd === "pre") {
        this.subTabKey -= 1;
      } else if (cmd === "next") {
        this.subTabKey += 1;
      }
    },
    changeSubTab(index) {
      this.subTabKey = +index;
    },
    startClickHandle() {
      this.$router.push({
        path: "/super-read/check-point",
        query: { type: this.detail.question_type },
      });
    },

    subAnswer() {
      handUpQuestion({
        question_id: this.detail.id,
        question_type: "1",
        select_option: this.subjects.map((v) => v.answer).toString(),
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$router.push({
            path: "/super-read/report",
            query: { id: this.detail.id },
          });
        } else {
          this.$message.error(res.info);
        }
      });
    },
    quitStudy() {
      this.$yxpConfirm({
        msg: "是否退出",
      })
        .then(() => {
          // this.$router.push({
          //   path: '/super-read/check-point',
          //   query: {type: this.$route.query.type,isnew:this.isnew,parent_id:this.parent_id,id:this.package_id,title:this.title}
          // })
          this.$router.go(-1);
        })
        .catch(() => {});
    },

    subTitleClick(e) {
      let el = $(e.srcElement);
      // 点击滚动到顶部 滚动高 - 距离高 - 顶部固定高
      $("#selectSection").scrollTop(
        $("#selectSection").scrollTop() + el.position().top - 80
      );
    },
    bodyClick(e) {
      if (e === 'body') {
        this.indexShow = -1
        this.visibleKey = "-1"
      }
      if (!window[`bs:event:scroll:close`]) {
        this.indexShow = -1
        this.visibleKey = "-1"
      }
    },
    scrollRmPop() {
        if (!window[`bs:event:scroll:close`]) {
            $(".ant-popover").empty();
            $('.ant-popover-open').removeClass('ant-popover-open')
        }
        // $(".ant-popover").hide();
        // setTimeout(() => {
        //   $(".ant-popover").show()
        // })
    },
  },
  created() {
    this.initList();
    this.isnew = this.$route.query.isnew;
    this.parent_id = this.$route.query.parent_id;
    this.package_id = this.$route.query.package_id;
    this.title = this.$route.query.title;
    // document.body.addEventListener("click", this.outPopClick);
    // document.addEventListener('scroll', this.scrollRmPop, true)
    document.addEventListener('scroll', this.bodyClick, true)
  },
  mounted() {
    this.audio = document.getElementById("reverse-audio");
  },
  beforeDestroy() {
    if (this.audio) {
      this.audio.pause()
    }
    // document.body.removeEventListener("click", this.outPopClick);
    // document.removeEventListener("scroll", this.scrollRmPop, true);
    document.removeEventListener("scroll", this.bodyClick, true);
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less" scope>
/* @import url(); 引入公共css类 */
@import url("./index.less");
</style>
